<script setup lang="ts">
  import { Picture } from '@element-plus/icons-vue'
  import { PropType, ref, watch } from 'vue'
  import { CodeScanSetData } from '../../../types'
  import { ElMessage, UploadFile, UploadRawFile } from 'element-plus'
  import _ from 'lodash'
  import ImgPreviewModal from '@/components/ImgPreviewModal.vue'

  const props = defineProps({
    sets: {
      type: Object as PropType<Array<CodeScanSetData>>,
      default: () => [],
    },
  })

  const emits = defineEmits<{
    (e: 'logoUpdate', value: UploadRawFile): void
    (e: 'logoDel'): void
    (e: 'update', value: Array<CodeScanSetData>): void
  }>()

  // 设置
  const sets = ref<Array<CodeScanSetData>>([])

  // 颜色选项
  const colorOptional = [
    { label: 'blue', value: '#007cff' },
    { label: 'green', value: '#00c0c0' },
    { label: 'purple', value: '#a06eff' },
    { label: 'red', value: '#f56c6c' },
    { label: 'orange', value: '#e69103' },
  ]

  // logo预览地址
  const logoLink = ref('')

  // 更新LOGO事件
  const handleLogoUpdate = (index: number, file: UploadRawFile) => {
    if (!['image/jpeg', 'image/png'].includes(file.type)) {
      ElMessage({
        showClose: true,
        type: 'error',
        message: '文件必须是JPG或PNG类型的文件',
      })
      return false
    }
    if (file.size / 1024 > 200) {
      ElMessage({
        showClose: true,
        type: 'error',
        message: '文件不能超过200kb',
      })
      return false
    }
    logoLink.value = URL.createObjectURL(file)
    sets.value[index].val = logoLink.value
    emits('logoUpdate', file)
    delayedUpdate()
  }

  // 删除LOGO事件
  const handleLogoDel = (index: number) => {
    logoLink.value = ''
    sets.value[index].val = ''
    emits('logoDel')
    delayedUpdate()
  }

  // 修改页面颜色事件
  const handleColorChange = (index: number, color: string) => {
    sets.value[index].val = color
    delayedUpdate()
  }

  // 图片预览弹窗标题
  const imgPreviewModalTitle = ref('')

  // 图片预览弹窗显示状态
  const imgPreviewModalVisible = ref(false)

  // 图片预览事件
  const handlePreviewImage = (url: string, name = '') => {
    if (!url) {
      ElMessage({
        showClose: true,
        type: 'warning',
        message: '暂无图片可预览',
      })
      return false
    }
    logoLink.value = url
    imgPreviewModalTitle.value = name
    imgPreviewModalVisible.value = true
  }

  // 按钮取消聚焦事件
  const handleCancelFocus = (e: Event) => {
    ;(e.target as HTMLButtonElement).blur()
  }

  // 延迟发送新的设置
  const delayedUpdate = _.debounce(() => {
    emits('update', _.cloneDeep(sets.value))
  }, 150)

  watch(
    props,
    (value) => {
      sets.value = _.cloneDeep(value.sets)
      value.sets.forEach((field) => {
        if (field.dataType === 3 && typeof field.val === 'string') {
          logoLink.value = field.val
        }
      })
    },
    { deep: true, immediate: true },
  )
</script>

<template>
  <div>
    <template v-for="(set, index) in sets" :key="set.name">
      <template v-if="set.dataType === 1">
        <el-form label-position="right">
          <!--页面颜色-->
          <el-form-item :label="`${set.name}`" class="mt-10">
            <el-input v-model.trim="set.val" @input="delayedUpdate" />
          </el-form-item>

          <el-form-item class="mt-10" label="推荐色调">
            <div class="recommend_color">
              <template v-for="color in colorOptional" :key="color.label">
                <div
                  :class="['color_item', color.label]"
                  @click="handleColorChange(index, color.value)"
                ></div>
              </template>
            </div>
          </el-form-item>
        </el-form>
      </template>

      <template v-if="set.dataType === 2">
        <el-form>
          <!--右侧标题-->
          <el-form-item :label="`${set.name}`" class="mt-10">
            <el-input v-model.trim="set.val" @input="delayedUpdate" />
          </el-form-item>
        </el-form>
      </template>

      <template v-if="set.dataType === 3">
        <el-form>
          <!--左侧图标-->
          <el-form-item :label="`${set.name}`" class="mt-10">
            <div>
              <el-image :src="logoLink" style="width: 100px; height: 100px">
                <template #error>
                  <div class="image-slot">
                    <el-icon>
                      <Picture></Picture>
                    </el-icon>
                  </div>
                </template>
              </el-image>
              <div style="display: flex; gap: 10px">
                <el-upload
                  :auto-upload="false"
                  :on-change="(file: UploadFile) => handleLogoUpdate(index, file.raw)"
                  :show-file-list="false"
                >
                  <el-button
                    class="upload_btn"
                    style="width: 3.2vw"
                    type="primary"
                    @focus="handleCancelFocus"
                    >上传
                  </el-button>
                </el-upload>
                <el-button
                  style="width: 3.2vw"
                  @click="handlePreviewImage(logoLink)"
                  @focus="handleCancelFocus"
                  >预览
                </el-button>
                <el-button
                  style="width: 3.2vw; margin: 0"
                  plain
                  type="danger"
                  @click="handleLogoDel(index)"
                  @focus="handleCancelFocus"
                  >删除
                </el-button>
              </div>
              <div class="upload_logo_tip">
                上传格式为 .jpg 或
                .png，大小不超过200Kb的图片作为活动页面背景图。建议图片尺寸为40像素×40像素
              </div>
            </div>
          </el-form-item>
        </el-form>
      </template>

      <!--登记按钮-->
      <template v-if="set.dataType === 4">
        <el-form>
          <el-form-item :label="`${set.name}`" class="mt-10">
            <div class="flex-center-5">
              <el-switch v-model="set.show" @change="delayedUpdate" />
              <template v-if="set.show">显示</template>
              <template v-else>隐藏</template>
            </div>
          </el-form-item>
        </el-form>
      </template>

      <!--报修按钮-->
      <template v-if="set.dataType === 5">
        <el-form>
          <el-form-item :label="`${set.name}`" class="mt-10">
            <div class="flex-center-5">
              <el-switch v-model="set.show" @change="delayedUpdate" />
              <template v-if="set.show">显示</template>
              <template v-else>隐藏</template>
            </div>
          </el-form-item>
        </el-form>
      </template>
    </template>
    <ImgPreviewModal
      v-model="imgPreviewModalVisible"
      :name="imgPreviewModalTitle"
      :url="logoLink"
    />
  </div>
</template>

<style scoped lang="scss">
  .upload_btn {
    width: 2.8vw;
    background-color: $primaryColor;
    border-color: $primaryColor;

    &:hover {
      background-color: rgba($primaryColor, 0.8);
      border-color: rgba($primaryColor, 0.8);
    }
  }

  .image-slot {
    background: #f5f7fa;
    color: #909399;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
  }

  .upload_logo_tip {
    font-size: 12px;
    color: #999;
    line-height: 20px;
  }

  .mt-10 {
    margin-bottom: 10px;
  }

  .flex-center-5 {
    display: flex;
    align-items: center;
    gap: 5px;
  }

  .recommend_color {
    display: flex;
    gap: 10px;
    align-items: center;

    .color_item {
      width: 16px;
      height: 16px;
      border-radius: 4px;
      cursor: pointer;
    }

    .blue {
      background-color: $primaryColor;
    }

    .red {
      background-color: $deleteColor;
    }

    .green {
      background-color: $secondColor3;
    }

    .purple {
      background-color: $secondColor1;
    }

    .orange {
      background-color: $secondColor2;
    }
  }
</style>
